package com.tianwen.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianwen.management.config.JwtHelper;
import com.tianwen.management.entity.LoginUser;
import com.tianwen.management.entity.Role;
import com.tianwen.management.entity.User;
import com.tianwen.management.entity.UserRolePermission;
import com.tianwen.management.service.UserRolePermissionService;
import com.tianwen.management.service.UserService;
import com.tianwen.management.mapper.UserMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author Administrator
* @description 针对表【user】的数据库操作Service实现
* @createDate 2023-05-12 15:34:17
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
@Resource
private UserMapper userMapper;
@Resource
private UserRolePermissionService userRolePermissionService;
@Resource
private AuthenticationManager authenticationManager;
@Resource
private RedisTemplate  redisTemplate;
    @Override
    public List<User> page(Integer page, Integer pageSize, String username)
    {
        QueryWrapper<User> queryWrap=new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(username)){
            queryWrap.like("username",username);
        }
        queryWrap.orderByDesc("id" );
        Page<User> pageInfo=new Page<>(page,pageSize);
        List<User> userList = userMapper.selectPage(pageInfo, queryWrap).getRecords();
        return userList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveAndRole(User user) {
        userMapper.insert(user);
        user.getRoleList().stream().forEach(role->{
            role.getPermissionList().stream().forEach(permission -> {
                UserRolePermission userRolePermission=new UserRolePermission();
                userRolePermission.setRoleId(role.getId());
                userRolePermission.setUserId(user.getId());
                userRolePermission.setPermissionId(permission.getId());
                userRolePermission.setIsUser(1);
                userRolePermissionService.save(userRolePermission);
            });
        });
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeAndRole(Long id) {
        QueryWrapper<UserRolePermission> queryWrap=new QueryWrapper<>();
        queryWrap.eq("user_id",id);
        queryWrap.eq("is_user",1);
        userRolePermissionService.remove(queryWrap);
        userMapper.deleteById(id);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateAndRole(User user) {
        QueryWrapper<UserRolePermission> queryWrap = new QueryWrapper<>();
        queryWrap.eq("user_id", user.getId());
        queryWrap.eq("is_user",1);
        userRolePermissionService.remove(queryWrap);
        user.getRoleList().stream().forEach(role->{
            role.getPermissionList().stream().forEach(permission -> {
                UserRolePermission userRolePermission=new UserRolePermission();
                userRolePermission.setRoleId(role.getId());
                userRolePermission.setUserId(user.getId());
                userRolePermission.setPermissionId(permission.getId());
                userRolePermission.setIsUser(1);
                userRolePermissionService.save(userRolePermission);
            });
        });
        userMapper.updateById(user);
        return true;
    }

    @Override
    public Map login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        if(ObjectUtils.isEmpty(authentication)){
            throw new RuntimeException("认证失败");
        }
        LoginUser loginUser =(LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();

        redisTemplate.opsForValue().set("user:"+id.toString(),loginUser);

        String token = JwtHelper.createToken(id, null);
         Map<String,String> map=new HashMap<>();
        map.put("token",token);
        System.err.println("登录成功");
        return map;
    }

    @Override
    public Boolean logout() {
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authenticationToken.getPrincipal();
        redisTemplate.delete("user:"+loginUser.getUser().getId());
        return true;
    }


}




